package com.iknight.theory.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iknight.mgr.core.utils.IkgDateUtils;
import com.iknight.mgr.core.utils.IkgStringUtils;
import com.iknight.theory.api.TeRecordService;
import com.iknight.theory.mapper.TPTranPDeMapper;
import com.iknight.theory.mapper.TeRecordMapper;
import com.iknight.theory.model.SegPowerInfo;
import com.iknight.theory.model.TPRecordModel;
import com.iknight.theory.model.TPTranPDeModel;
import com.iknight.theory.model.TPowerTranModel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TeRecordServiceImpl implements TeRecordService<TPRecordModel, String> {
    private final static Logger logger = LogManager.getLogger(TeRecordServiceImpl.class);
    @Autowired
    private TeRecordMapper<TPRecordModel, String> teRecordMapper;
    @Autowired
    private TPTranPDeMapper<TPTranPDeModel, String> tpTranPDeMapper;

    @Override
    public void batchSave(List<TPRecordModel> entities) {
        for (TPRecordModel entity : entities) {
            this.save(entity);
        }
    }

    @Override
    public List<Map> getPowerByParam(Map param) {
        return teRecordMapper.getPowerByParam(param);
    }

    @Override
    public PageInfo<Map> getConsPowerByParam(Map param) {
        int pageSize = Integer.parseInt(param.get("pagesize").toString());
        int pageStart = Integer.parseInt(param.get("pagestart").toString());
        PageHelper.startPage(pageStart, pageSize, true);
        List<Map> result = teRecordMapper.getConsPowerByParam(param);
        return new PageInfo<>(result);
    }

    /**
     * 保存计算结果，对原记录进行删除，保持数据最新，增加事务支持
     *
     * @param entity
     * @param entities
     */
    @Transactional
    @Override
    public void saveCaledTranPower(TPowerTranModel entity, TPTranPDeModel tpTranPDeModel, List<SegPowerInfo> entities) {
        //刪除原记录
        String tranId = entity.getTran_id();
        teRecordMapper.removeSegRecordByTranId(tranId); //从记录删除
        teRecordMapper.removeTranRecordByTranId(tranId);//主记录删除
        tpTranPDeMapper.delete(tranId);

        tpTranPDeMapper.insert(tpTranPDeModel);
        teRecordMapper.saveTranPower(entity);
        for (SegPowerInfo info : entities) {
            teRecordMapper.saveSegPower(info);
        }
    }

    @Override
    public PageInfo<Map> getTranPowerData(Map param) {
        int pageSize = Integer.parseInt(param.get("pagesize").toString());
        int pageStart = Integer.parseInt(param.get("pagestart").toString());

        PageHelper.startPage(pageStart, pageSize, true);
        List<Map> result = teRecordMapper.getTranPowerData(param);
        PageInfo<Map> pageInfo = new PageInfo<>(result);
        return pageInfo;
    }

    @Transactional
    @Override
    public void removePowerDataByRecord(String recordId) {
        teRecordMapper.removeDataByMainRecordId(recordId);
        teRecordMapper.removeDataByRecordId(recordId);
    }

    @Override
    public PageInfo<Map> getSegPowerByRecord(Map param) {
        int pageSize = Integer.parseInt(param.get("pagesize").toString());
        int pageStart = Integer.parseInt(param.get("pagestart").toString());
        String recordId = IkgStringUtils.ObjectToString(param.get("record_id"));
        PageHelper.startPage(pageStart, pageSize, true);
        List<Map> result = teRecordMapper.getSegPowerByRecordId(recordId);
        return new PageInfo<>(result);
    }

    @Override
    public Object getCalLogByRecordId(String recordId) {
        return teRecordMapper.getCalLogByRecordId(recordId);
    }

    @Override
    public List<Map> getSegPowerByMainRecordId(Map param) {
        String mainRecordId = IkgStringUtils.ObjectToString(param.get("record_id"));
        return teRecordMapper.getSegPowerByRecordId(mainRecordId);
    }

    @Override
    public List<Map> getTranPowerByRecordId(Map param) {
        return teRecordMapper.getTranPowerData(param);
    }

    @Override
    public List<Map> getTranPowerByParam(Map param) {
        String startDate = IkgStringUtils.ObjectToString(param.get("start_date"));
        String endDate = IkgStringUtils.ObjectToString(param.get("end_date"));
        //如果开始日期为空，则自动取当前日期所在年度的一月一日
        //如果结束日期为空，则自动去当前日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        if (startDate.trim().length() == 0) {
            SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
            startDate = sdfYear.format(calendar.getTime()) + "-01-01";
            param.put("start_date", startDate);
        }
        if (endDate.trim().length() == 0) {
            endDate = sdf.format(calendar.getTime());
            param.put("end_date", endDate);
        }
        //获得查询的结果
        List<Map> result = teRecordMapper.getTranPowerByParam(param);
        List<String> dateLs = new ArrayList<>();
        List<Map> resultLs = new ArrayList<>();
        try {
            dateLs = IkgDateUtils.getDatePeriodList(startDate, endDate, IkgDateUtils.DAY);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //默认初始化数据
        for (String date : dateLs) {
            Map tempMap = new HashMap();
            tempMap.put("data_date", date);
            tempMap.put("data_value", 0);
            tempMap.put("data_k1_value",0);
            tempMap.put("data_k2_value",0);
            tempMap.put("data_k3_value",0);

            for (int i = 0; i < result.size(); i++) {
                Map resultMap = result.get(i);
                if (IkgStringUtils.ObjectToString(resultMap.get("data_date")).equals(date)) {
                    tempMap.put("data_value", resultMap.get("power_rate"));
                    tempMap.put("data_k1_value",resultMap.get("rate_k1"));
                    tempMap.put("data_k2_value",resultMap.get("rate_k2"));
                    tempMap.put("data_k3_value",resultMap.get("rate_k3"));

                    //清除指定元素，减少循环
                    Iterator<Map> it = result.iterator();
                    while (it.hasNext()) {
                        Map itMap = it.next();
                        if (itMap.get("data_date").equals(resultMap.get("data_date"))) {
                            it.remove();
                        }
                    }
                }
            }
            resultLs.add(tempMap);
        }
        return resultLs;
    }

    @Override
    public void save(TPRecordModel record) {
        teRecordMapper.insert(record);
    }

    @Override
    public void delete(String pkey) {
        teRecordMapper.delete(pkey);
    }

    @Override
    public TPRecordModel selectOne(String pkey) {
        return teRecordMapper.selectOne(pkey);
    }

    @Override
    public PageInfo<TPRecordModel> selectPage(Map<String, Object> params, int pageStart, int pageSize) {
        PageHelper.startPage(pageStart, pageSize, true);
        List<TPRecordModel> result = teRecordMapper.selectByCond(params);
        PageInfo<TPRecordModel> page = new PageInfo<>(result);
        return page;
    }
}
